<template>
  <div class="view-fill">
    <div
      v-if="
        !modifyInfo.visible &&
        !modifyByDeliverInfo.visible &&
        !modifyByPurchInfo.visible &&
        !modifyByContractInfo.visible
      "
      class="app-container-flex"
    >
      <NewFullScreen
        v-model="showDialog"
        title="收货明细"
        :needOperateAffair="true"
        :operateAffairData="affairTableInfo"
        @returnBack="returnBack"
      >
        <template v-slot:full-button>
          <el-button
            v-if="
              $permission('assetReceiving:submit') && infoList.data.status === 1
            "
            @click="submit"
            >提交</el-button
          >
          <el-button
            v-if="
              $permission('assetReceiving:update') &&
              infoList.data.status === 1 &&
              infoList.data.receiveOrderSourceType === -2
            "
            @click="update"
            >修改</el-button
          >
          <el-button
            v-if="
              $permission('assetReceiving:update') &&
              infoList.data.status === 1 &&
              infoList.data.receiveOrderSourceType === 18
            "
            @click="updateByDeliver"
            >修改</el-button
          >
          <el-button
            v-if="
              $permission('assetReceiving:update') &&
              infoList.data.status === 1 &&
              infoList.data.receiveOrderSourceType === 0
            "
            @click="updateByPurch"
            >修改</el-button
          >
          <el-button
            v-if="
              $permission('assetReceiving:update') &&
              infoList.data.status === 1 &&
              infoList.data.receiveOrderSourceType === 61
            "
            @click="updateByContract"
            >修改</el-button
          >
          <el-button
            v-if="
              $permission('assetReceiving:confirm') &&
              infoList.data.status === 2
            "
            @click="confirm"
            >确认</el-button
          >
          <el-button
            v-if="
              $permission('assetReceiving:revoke') && infoList.data.status === 2
            "
            @click="revoke"
            >撤回</el-button
          >
          <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="canPrint"
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="print"
          ></PopoverPrint>
          <!--  <el-button
            v-if="
              $permission('assetReceiving:printDetail') &&
              infoList.data.status !== 1
            "
            @click="print"
            >打印</el-button
          > -->
          <el-button
            v-if="
              $permission('assetReceiving:exportDetail') &&
              infoList.data.status !== 1
            "
            @click="exportExcel"
            >导出excel</el-button
          >
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="infoList">
              <template v-slot:basic-purchOrderNo>
                <span
                  v-if="
                    $permission('purchOrder:detail') &&
                    infoList.data.purch_application_show
                  "
                  @click="showPurchOrderpDetail(infoList.data.purchOrderId)"
                  >{{ infoList.data.purchOrderNo || '-' }}</span
                >
                <span v-else>{{ infoList.data.purchOrderNo || '-' }}</span>
              </template>
              <template v-slot:basic-billNumberList>
                <div
                  v-if="
                    infoList.data.billNumberList &&
                    infoList.data.billNumberList.length > 0
                  "
                >
                  <span
                    v-for="(item, index) in infoList.data.billNumberList"
                    :key="index"
                  >
                    <a
                      v-if="index <= 1"
                      class="slip-edit"
                      @click="showreceiptDetail(item.id)"
                      >{{ item.billCode }}</a
                    >
                    <span
                      v-if="
                        index < 1 && infoList.data.billNumberList.length > 1
                      "
                      >,</span
                    >
                  </span>
                  <el-dropdown
                    v-if="infoList.data.billNumberList.length > 2"
                    @command="showreceiptDetail"
                  >
                    <span class="el-dropdown-link slip-edit">
                      更多
                      <i class="el-icon-arrow-down el-icon--right"></i>
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item
                          v-for="item in infoList.data.billNumberList"
                          :key="item.id"
                          :command="item.id"
                          >{{ item.billCode }}</el-dropdown-item
                        >
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
                <span v-else>-</span>
              </template>
              <template v-slot:basic-invoiceNumber>
                <div
                  v-if="
                    infoList.data.invoiceNumberList &&
                    infoList.data.invoiceNumberList.length > 0
                  "
                  style="wordwrap: break-word"
                >
                  <span
                    v-for="(item, index) in infoList.data.invoiceNumberList"
                    :key="index"
                  >
                    <a v-if="index <= 1">{{ item }}</a>
                    <span
                      v-if="
                        index < 1 && infoList.data.invoiceNumberList.length > 1
                      "
                      >,</span
                    >
                  </span>
                  <el-dropdown
                    v-if="infoList.data.invoiceNumberList.length > 2"
                  >
                    <span class="el-dropdown-link">
                      更多
                      <i class="el-icon-arrow-down el-icon--right"></i>
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item
                          v-for="(item, index) in infoList.data
                            .invoiceNumberList"
                          :key="index"
                          >{{ item }}</el-dropdown-item
                        >
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
                <span v-else>-</span>
              </template>
              <template v-slot:basic-remark>
                <el-input
                  v-if="
                    (infoList.data.status === 'pend_storage' && checkRemark) ||
                    (infoList.data.status === 'complete' && checkRemark)
                  "
                  v-model="infoList.data.remark"
                  type="textarea"
                  placeholder="请输入备注"
                  :autosize="{ minRows: 1, maxRows: 5 }"
                  style="width: 50%"
                />
                <span
                  v-else
                  :class="
                    (infoList.data.status === 'pend_storage' && !checkRemark) ||
                    (infoList.data.status === 'complete' && !checkRemark)
                      ? 'slip-edit'
                      : ''
                  "
                  @click="moifyRemark"
                  >{{ infoList.data.remark || '-' }}</span
                >
              </template>
            </basic-information>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')"></Tooltip>
          </div>
          <div class="model-panel-body">
            <div class="flex_full_item">
              <!-- 表格 -->
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :check-box="false"
                :tab-index="true"
                :summary-field-list="tableInfo.summaryFieldList"
                :field-list="tableInfo.fieldList"
                :isDynamic="true"
              >
              </page-table>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <order-modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :id="modifyInfo.id"
      @returnModify="returnModify"
    />
    <ModifyByDeliver
      v-if="modifyByDeliverInfo.visible"
      :deliver-id="modifyByDeliverInfo.deliverId"
      :order-id="modifyByDeliverInfo.orderId"
      v-model:visible="modifyByDeliverInfo.visible"
      :title="modifyByDeliverInfo.title"
      @returnModify="returnModify"
    />
    <ModifyByPurch
      v-if="modifyByPurchInfo.visible"
      :purch-id="modifyByPurchInfo.purchId"
      :order-id="modifyByPurchInfo.orderId"
      v-model:visible="modifyByPurchInfo.visible"
      :title="modifyByPurchInfo.title"
      @returnModify="returnModify"
    />
    <ModifyByContract
      v-if="modifyByContractInfo.visible"
      :contractId="modifyByContractInfo.contractId"
      :order-id="modifyByContractInfo.orderId"
      v-model:visible="modifyByContractInfo.visible"
      :title="modifyByContractInfo.title"
      @returnModify="returnModify"
    />
    <purch-receipt-detail
      v-if="receiptDetailsInfo.visible"
      :id="receiptDetailsInfo.id"
      v-model:visible="receiptDetailsInfo.visible"
      :title="receiptDetailsInfo.title"
    />
  </div>
</template>

<script setup name="OtherDetail">
import { getCustomizeSetting } from '@/api/customize'
import { orderOpAffairAll } from '@/api/affair'
import {
  revokeReceive,
  confirmReceive,
  submitReceive,
  getReceiveById,
  getReceiveDetailsAll,
  receivePrintOrder,
  receiveExcelOrder,
} from '@/api/asset'
import { doPrint } from '@/utils/exportUtil.js'
import { selectByCodeAndDept } from '@/api/report.js'
import { updatePrintCount } from '@/api/mapping'
const OrderModify = defineAsyncComponent(() => import('./modify'))
const ModifyByDeliver = defineAsyncComponent(() => import('./modifyByDeliver'))
const ModifyByPurch = defineAsyncComponent(() => import('./modifyByPurch'))
const ModifyByContract = defineAsyncComponent(() =>
  import('./modifyByContract')
)
const purchReceiptDetail = defineAsyncComponent(() =>
  import('@/views/purch/receipt/details.vue')
)

const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps(['visible', 'id', 'sourceType'])
const infoList = ref({
  data: {},
  fieldList: [
    { label: '收货单号', value: 'orderNo', type: 'text' },
    {
      label: '采购单号',
      value: 'purchOrderNo',
      type: 'slot',
      show: false,
    },
    {
      label: '发货单号',
      value: 'deliverOrderNo',
      type: 'text',
      show: false,
    },
    { label: '收货部门', value: 'deptName', type: 'text' },
    { label: '供应商', value: 'supplierName', type: 'text' },
    { label: '收货人', value: 'receivingUserName', type: 'text' },
    { label: '收货时间', value: 'receivingTime', type: 'text' },
    {
      label: '收货联系人',
      value: 'receivingContacts',
      type: 'text',
    },
    {
      label: '联系人电话',
      value: 'receivingPhone',
      type: 'text',
    },

    {
      label: '收票单号',
      value: 'billNumberList',
      type: 'slot',
    },
    { label: '发票号码', value: 'invoiceNumber', type: 'slot' },
    { label: '状态', value: 'statusValue', type: 'text' },
    { label: '备注', value: 'remark', type: 'popover' },
  ],
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id,
      },
    },
    queryParams: {},
  },
})
const modifyInfo = ref({
  visible: false,
  title: '',
  id: '',
})
const modifyByDeliverInfo = ref({
  visible: false,
  orderId: '',
  deliverId: '',
  title: '',
})
const modifyByPurchInfo = ref({
  visible: false,
  orderId: '',
  purchId: '',
  title: '',
})
const modifyByContractInfo = ref({
  visible: false,
  orderId: '',
  contractId: '',
  title: '',
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
})
const affairTableInfo = ref({
  api: orderOpAffairAll,
  query: {
    orderType: 15,
    orderId: props.id,
    sort: 'operate_time desc',
  },
})
const receiptDetailsInfo = ref({
  id: '',
  visible: false,
})
const formInfoData = ref({})

const canPrint = computed(() => {
  return (
    proxy.$permission('assetReceiving:printDetail') &&
    infoList.value.data.status !== 1
  )
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})

setData()
function setData() {
  let obj = {
    orderNo: {
      label: '单号',
      value: 'orderNo',
      componentType: 'input',
      show: false,
      type: 'column',
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...obj,
  })
  getCustomize()
}
function returnModify() {
  getMain()
  getList()
}

//提交
function submit() {
  let ids = [infoList.value.data.id]
  submitReceive(ids).then((res) => {
    if (res && res.success) {
      returnModify()
    }
  })
}
//撤回
function revoke() {
  let ids = [infoList.value.data.id]
  revokeReceive(ids).then((res) => {
    if (res && res.success) {
      returnModify()
    }
  })
}
//完成
function confirm() {
  confirmReceive([infoList.value.data.id]).then((res) => {
    if (res && res.success) {
      returnModify()
    }
  })
}
//修改
function update() {
  modifyInfo.value.id = infoList.value.data.id
  modifyInfo.value.title = '修改出库单'
  modifyInfo.value.visible = true
}
function updateByDeliver() {
  //发货单
  modifyByDeliverInfo.value.visible = true
  modifyByDeliverInfo.value.deliverId = ''
  modifyByDeliverInfo.value.orderId = infoList.value.data.id
  modifyByDeliverInfo.value.title = '修改收货单'
}
function updateByPurch() {
  //采购单
  modifyByPurchInfo.value.visible = true
  modifyByPurchInfo.value.purchId = ''
  modifyByPurchInfo.value.orderId = infoList.value.data.id
  modifyByPurchInfo.value.title = '修改收货单'
}
function updateByContract() {
  //合同单
  modifyByContractInfo.value.visible = true
  modifyByContractInfo.value.contractId = ''
  modifyByContractInfo.value.orderId = infoList.value.data.id
  modifyByContractInfo.value.title = '修改收货单'
}

function showreceiptDetail(id) {
  //发票管理
  receiptDetailsInfo.value.visible = true
  receiptDetailsInfo.value.id = id
}
function returnBack() {
  emits('returnBack', false)
}
function getMain() {
  getReceiveById(props.id).then((resp) => {
    if (resp && resp.success) {
      let data = resp.data
      if (data.receiveOrderSourceType === 1) {
        showFieldListItem(false, 'purchOrderNo')
        showFieldListItem(false, 'deliverOrderNo')
      } else if (data.receiveOrderSourceType === 2) {
        showFieldListItem(true, 'purchOrderNo')
        showFieldListItem(false, 'deliverOrderNo')
      } else if (data.receiveOrderSourceType === 3) {
        showFieldListItem(true, 'purchOrderNo')
        showFieldListItem(true, 'deliverOrderNo')
      }
      infoList.value.data = resp.data
      infoList.value.data.invoiceNumberList = infoList.value.data.invoiceNumber
        ? infoList.value.data.invoiceNumber.indexOf(',') !== -1
          ? infoList.value.data.invoiceNumber.split(',')
          : [infoList.value.data.invoiceNumber]
        : []
    }
  })
}
function showFieldListItem(show, nameValue) {
  let fieldList = infoList.value.fieldList
  fieldList.map((item) => {
    if (item.value === nameValue) {
      item.show = show
    }
  })
}
function getList() {
  getReceiveDetailsAll(filterInfo.value.query).then((resp) => {
    if (resp && resp.success) {
      tableInfo.value.data = resp.data
    }
  })
}
const templateArr = ref([])
const popoverVisible = ref(false)
//打印
function print() {
  selectByCodeAndDept({
    tempCode: 'assetReceivingDetail',
    deptId: infoList.value.data.deptId,
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {
            orderId: props.id,
            orderNo: infoList.value.data.orderNo,
          },
          callback: printCallback,
          printCount: true,
          data: {},
        })
      }
    }
  })
}
function printCallback() {
  try {
    // 打印成功增加打印次数
    updatePrintCount({
      orderNo: infoList.value.data.orderNo,
      orderId: props.id,
      tempCode: 'assetReceivingDetail',
      orderType: 15,
    })
  } catch (error) {}
}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      orderId: props.id,
      orderNo: infoList.value.data.orderNo,
    },
    callback: printCallback,
    printCount: true,
    data: {},
  })
  popoverVisible.value = false
}
function getPrintData(temp) {
  let tableKey = ''
  if (props.sourceType == -2) {
    tableKey =
      'assetReceivingDetails-com.slip.spd.entity.vo.asset.AssetReceivingOrderDetailVO'
  } else if (props.sourceType == 0) {
    //采购
    tableKey =
      'assetReceivingDetailsByPurch-com.slip.spd.entity.vo.asset.AssetReceivingOrderDetailVO'
  } else if (props.sourceType == 61) {
    //合同
    tableKey =
      'assetReceivingDetailsByContract-com.slip.spd.entity.vo.asset.AssetReceivingOrderDetailVO'
  } else if (props.sourceType == 18) {
    //发货
    tableKey =
      'assetReceivingDetailsByDeliver-com.slip.spd.entity.vo.asset.AssetReceivingOrderDetailVO'
  } else if (props.sourceType == 4) {
    tableKey =
      'assetReceivingDetails-com.slip.spd.entity.vo.asset.AssetReceivingOrderDetailVO'
  }
  let params = {
    tableKey: tableKey,
    orderIds: [props.id],
  }
  receivePrintOrder(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}
//导出excel
function exportExcel() {
  receiveExcelOrder(filterInfo.value.query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
function getCustomize() {
  let tableKey = ''
  if (props.sourceType == -2) {
    tableKey =
      'assetReceivingDetails-com.slip.spd.entity.vo.asset.AssetReceivingOrderDetailVO'
  } else if (props.sourceType == 0) {
    //采购
    tableKey =
      'assetReceivingDetailsByPurch-com.slip.spd.entity.vo.asset.AssetReceivingOrderDetailVO'
  } else if (props.sourceType == 61) {
    //合同
    tableKey =
      'assetReceivingDetailsByContract-com.slip.spd.entity.vo.asset.AssetReceivingOrderDetailVO'
  } else if (props.sourceType == 18) {
    //发货
    tableKey =
      'assetReceivingDetailsByDeliver-com.slip.spd.entity.vo.asset.AssetReceivingOrderDetailVO'
  } else if (props.sourceType == 4) {
    tableKey =
      'assetReceivingDetails-com.slip.spd.entity.vo.asset.AssetReceivingOrderDetailVO'
  }
  let param = {
    tableKey: tableKey,
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      let obj = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail,
        true
      )
      tableInfo.value.fieldList = obj.fieldList
      getMain()
      getList()
    }
  })
}
</script>

<style scoped></style>
